#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from airtest.core.android.android import Android
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from datetime import datetime
import random
import time
import os
import sys


# 等待随机时间
print('Script Start...')
print('Wait random time...')
random_time = random.randrange(1, 600)
for sec in range(random_time):
    remain_time = random_time - sec
    if remain_time % 10 == 0 and remain_time > 3:
        print('Time left {0} seconds...'.format(remain_time))
    elif remain_time <= 5:
        print('Time left {0} seconds...'.format(remain_time))
    time.sleep(1)

# 删除多余的jpg文件
print('Delete jpg files...')
file_path = os.path.abspath(__file__)
dir_path = os.path.dirname(file_path)
for roots, dirs, files in os.walk(dir_path):
    for file in files:
        if file.split('.')[-1] == 'jpg':
            jpg_path = os.path.join(dir_path, file)
            os.remove(jpg_path)


poco = AndroidUiautomationPoco(force_restart=False)
timeout_time = 120
now_time = datetime.now()
now_hour = now_time.hour
serial_no = 'T3Q4C16801002945'
app_name = 'com.ztgame.tw'

# 初始化android手机
print('Initialize Android Mobile Device...')
device = Android(serialno=serial_no)

# 唤醒手机
device.wake()
time.sleep(3)
device.home()
time.sleep(3)

# 启动MUST
device.stop_app(package=app_name)
time.sleep(5)
device.start_app(package=app_name)
time.sleep(10)

# 点击HOME按钮
discover_button = poco("com.ztgame.tw:id/tv_find")
discover_button.wait_for_appearance(timeout=timeout_time)
discover_button.click()

# 点击打卡考勤按钮
signin_button = poco(text="打卡考勤")
signin_button.wait_for_appearance(timeout=timeout_time)
signin_button.click()

# 点击可签到点下拉框
sign_address_drop = poco("com.ztgame.tw:id/work_address_tv")
sign_address_drop.wait_for_appearance(timeout=timeout_time)
sign_address_drop.click()

# 点击松江二期按钮
songjiang_no2_button = poco("com.ztgame.tw:id/listView").offspring("android.widget.LinearLayout")[1]
songjiang_no2_button.wait_for_appearance(timeout=timeout_time)
songjiang_no2_button.click()

# 点击上班打卡
workon_button = poco("com.ztgame.tw:id/work_on_btn")
workon_button.wait_for_appearance(timeout=timeout_time)
workon_button.click()

# 点击提交按钮
submit_button = poco("com.ztgame.tw:id/submit_btn")
submit_button.wait_for_appearance(timeout=timeout_time)
submit_button.click()

# 点击确定按钮
try:
    ok_button = poco("com.ztgame.tw:id/btn_right")
    ok_button.wait_for_appearance(timeout=timeout_time)
    ok_button.click()
except Exception as e:
    print(e)
finally:
    time.sleep(5)
    # 关闭MUST
    device.home()
    time.sleep(5)
    device.stop_app(package=app_name)
    print('Finish Script...')
    sys.exit(0)
